package com.kylin.module.specials.actions;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.criterion.Order;

import com.kylin.common.Constants;
import com.kylin.common.dict.orm.Dict;
import com.kylin.common.entity.MsgKey;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.exception.SystemException;
import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.common.util.MemObjFactory;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.PropertyCondition;
import com.kylin.module.specials.business.SpecialBlogic;
import com.kylin.module.specials.forms.SpecialForm;
import com.kylin.module.specials.forms.SpecialPart;
import com.kylin.module.specials.orm.Special;
import com.kylin.struts.BaseActionInterface;
import com.kylin.struts.BaseDispatchAction;

/**
 * 专题部分功能的实现
 * 
 * @author DH
 * @version 01/16/08
 * @see com.kylin.struts.BaseDispatchAction
 * @see com.kylin.struts.BaseActionInterface
 */
public class SpecialAction extends BaseDispatchAction implements
		BaseActionInterface {

	protected static Logger log = Logger.getLogger(SpecialAction.class);

	/**
	 * 添加专题文章
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward add(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("开始添加专题");
		String forward = "addSucc";
		SpecialForm form = (SpecialForm) actionForm;
		try {
			SpecialBlogic blogic = new SpecialBlogic();
			blogic.addSpecial(form);
			// 返回成功的信息，需要在结果页面添加 <mytag:MyActionMsg />，也可以不使用此标签，直接在页面写成功信息
			request.setAttribute(Constants.MSGKEY, new MsgKey(
					"msg.addSpecial.succ", "专题保存成功"));
		} catch (Exception e) {
			// 参数传入 forward
			// 发生BusinessException异常后的结果页面和成功的页面相同，通过页面的
			// <mytag:MyActionMsg/>显示错误
			// 发生其它严重错误，则跳转到错误页，需要配置中定义<forward name="SystemException"
			// path="/common/errorPage.jsp" />
			doException(request, e, forward);
		}

		return mapping.findForward(forward);
	}

	/**
	 * 删除专题文章
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward delete(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("删除专题:" + request.getParameter("id"));
		String id = request.getParameter("id");

		try {
			SpecialBlogic blogic = new SpecialBlogic();
			blogic.deleteSpecialById(new Long(id));
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

		}
		// 不管执行成功失败都返回到列表，在列表页加入<mytag:MyActionMsg />显示处理结果
		return this.search(mapping, actionForm, request, response);
	}

	/**
	 * 查询专题文章列表
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward search(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("查询专题列表");
		String forward = "list";
		String searchId = request.getParameter("searchId");
		int pageSize = 15; // 分页列表的每页行数
		int pageNum = 1; // 当前页号
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {// 第一次查询，没有searchId（查询号）
				List conditions = new LinkedList();
				// -------构造查询条件--------//
				String language = request.getParameter("language");// 先创建个容器准备装条件
				if (language != null && !language.equals("")) {// 输入了查询条件：语言版本
					PropertyCondition cond = new PropertyCondition("language",
							language, PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}

				String catSpecialId = request.getParameter("catspecial");
				if (catSpecialId != null && !catSpecialId.equals("")) {// 输入了查询条件：专题分类
					Dict specialDict = new Dict(new Long(catSpecialId));
					PropertyCondition cond = new PropertyCondition(
							"catspecial", specialDict,
							PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}

				String keyword = request.getParameter("keyword");
				if (keyword != null && !keyword.equals("")) {// 输入了查询条件：关键字
					PropertyCondition cond = new PropertyCondition("title", "%"
							+ keyword + "%", PropertyCondition.OPERATOR_LIKE);
					conditions.add(cond);
					// cond = new PropertyCondition("content","%" + keyword +
					// "%",PropertyCondition.OPERATOR_LIKE);
					// conditions.add(cond);
				}
				// -----------接收查询条件结束----------//
				// 根据查询条件导出结果集
				cinfo = new CriteriaInfo(Special.class, conditions);
				cinfo.setOrderby(Order.desc("id"));
				addUserCacheCriteriaInfo(request, cinfo);
			} else {
				cinfo = getUserCacheCriteriaInfo(request, searchId);
			}
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum,
					cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
		} catch (Exception e) {
			// 参数传入 forward
			// 发生BusinessException异常后的结果页面和成功的页面相同，通过页面的<mytag:MyActionMsg
			// />显示错误
			// 发生其它严重错误，则跳转到错误页，需要配置中定义<forward name="SystemException"
			// path="/common/errorPage.jsp" />
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 查询10条热点专题文章
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward searchHot10(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) {
		log.debug("获得10条热点专题信息");
		String forward = "searchHot10";
		int pageSize = 10; // 分页列表的每页行数
		int pageNum = 1; // 当前页号
		CriteriaInfo cinfo = null;
		List conditions = null;
		try {
			conditions = new LinkedList();
			Locale lang = getSessionLocale(request);
			PropertyCondition cond = new PropertyCondition("language",lang.toString(),PropertyCondition.OPERATOR_EQ);
			conditions.add(cond);
			PropertyCondition cond_hot = new PropertyCondition("active",
					Special.ACTIVE_HOT, PropertyCondition.OPERATOR_EQ);
			conditions.add(cond_hot);

			cinfo = new CriteriaInfo(Special.class, conditions);
			cinfo.setOrderby(Order.desc("id"));
			addUserCacheCriteriaInfo(request, cinfo);
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum,
					cinfo);

			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
		} catch (BusinessException e) {
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 根据指定id获得需要编辑的专题
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward update(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		log.debug("修改专题的为id=" + request.getParameter("id"));
		String forward = "update";
		Special obj = null;
		try {
			if (id != null) {
				SpecialBlogic blogic = new SpecialBlogic();
				obj = blogic
						.getSpecialById(new Long(request.getParameter("id")));
			}
			request.setAttribute(Constants.KEY_REQUEST_RESULT, obj);
		} catch (Exception e) {
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 根据指定id更新专题
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward executeUpdate(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		log.debug("开始执行专题的修改" + id);
		String forward = "updateSucc";
		SpecialForm form = (SpecialForm) actionForm;
		try {
			if (id != null) {
				SpecialBlogic blogic = new SpecialBlogic();
				blogic.updateSpecial(form);
				request.setAttribute(Constants.MSGKEY, new MsgKey(
						"msg.addSpecial.succ", "专题修改成功"));
			}
		} catch (Exception e) {
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 查询专题文章详细信息
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward detailSpecial(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		log.debug("查看专题详细记录 : " + id);
		String forward = "detail";
		try {
			SpecialBlogic blogic = new SpecialBlogic();
			Special special = blogic.getSpecialById(new Long(id));
			request.setAttribute("special", special);
			System.out.println(special.getTitle());
			String _sort_name = special.getCatspecial().getName();
			request.setAttribute("sortName", _sort_name);
		} catch (Exception e) {
			doException(request, e, forward);
		}
		// 不管执行成功失败都跳转到详情页面
		return mapping.findForward(forward);
	}

	/**
	 * 查询所有热点专题
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward searchHot(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("查看所有热点专题");
		String forward = "hotList";
		String searchId = request.getParameter("searchId");
		int pageSize = 15; // 分页列表的每页行数
		int pageNum = 1; // 当前页号
		CriteriaInfo cinfo = null;
		List conditions = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {
				conditions = new LinkedList();
				PropertyCondition cond_hot = new PropertyCondition("active",
						Special.ACTIVE_HOT, PropertyCondition.OPERATOR_EQ);
				conditions.add(cond_hot);
			
				cinfo = new CriteriaInfo(Special.class, conditions);
				cinfo.setOrderby(Order.desc("id"));
				addUserCacheCriteriaInfo(request, cinfo);
			} else {
				cinfo = getUserCacheCriteriaInfo(request, searchId);
			}
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum,
					cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
		} catch (BusinessException e) {
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 热点增加
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward addHot(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int pageSize = 15;
		int pageNum = 1;
		String searchId = request.getParameter("searchId");
		String[] ids = request.getParameterValues("ids");
		if (ids == null) {
			ids = new String[] { request.getParameter("ids") };

		}
		log.info("添加为热点的数量为：" + ids.length);
		String forward = "list";
		List conditions = null;
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			SpecialBlogic blogic = new SpecialBlogic();
			blogic.toHot(ids);
			request.setAttribute(Constants.MSGKEY, new MsgKey("", "添加热点成功"));
			if (searchId == null) {
				cinfo = new CriteriaInfo(Special.class, conditions);
				cinfo.setOrderby(Order.desc("id"));
				addUserCacheCriteriaInfo(request, cinfo);
			} else {
				cinfo = getUserCacheCriteriaInfo(request, searchId);
			}
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum,
					cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
		} catch (Exception e) {
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 首页所有专题显示
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward index(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		String forward = "index";
		int partNum = 5; // 页面版块 5 个
		int num = 10; // 每个版块 10条记录
		List allData = new ArrayList();
		List list = MemObjFactory.getDict("专题类别", getSessionLocale(request).toString());
		try {
			SpecialBlogic blogic = new SpecialBlogic();
			if(list==null)
				throw new SystemException("系统缺少 专题类别字典("+getSessionLocale(request)+")");
			for (int i = 0; i < list.size() && i < partNum; i++) {
				Dict dict = (Dict) list.get(i);
				log.debug(" --- 按专题类别查询专题("+dict.getId()+")："+dict.getName());
				List specials = blogic.getListByCat(dict, num);
				if(specials != null)
				log.debug(" --- specials  ："+specials.size());
				else
					log.debug(" --- specials is null" );
				SpecialPart part = new SpecialPart(dict,specials);// 使用SpecialPart既保存了类别有保存了列表，方便页面使用
				allData.add(part);
			}
			request.setAttribute(Constants.KEY_REQUEST_RESULT, allData);
		} catch (Exception e) {
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 根据专题类别显示专题列表
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward listByCat(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) {
		String forward = "frontList";
		String catId = request.getParameter("id");
		String searchId = request.getParameter("searchId");
		int pageSize = 10;
		int pageNum = 1;
		CriteriaInfo cinfo = null;
		SpecialPart part = new SpecialPart();
		try {
			if (request.getParameter("pageSize") != null) {
				pageSize = Integer.parseInt(request.getParameter("pageSize"));
			}
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {
				List conditions = new LinkedList();
				SpecialBlogic blogic = new SpecialBlogic();
				Dict specialDict = blogic.getSpecialCatById(new Long(catId));
				part.setSpecialCat(specialDict);
				this.addCacheObject(request, "SpecialCat"+catId,specialDict);
				PropertyCondition cond = new PropertyCondition("catspecial",
						specialDict, PropertyCondition.OPERATOR_EQ);
				conditions.add(cond);
				cinfo = new CriteriaInfo(Special.class, conditions);
				cinfo.setPageSize(pageSize);
				cinfo.setOrderby(Order.desc("ordering").desc("createdon"));
				addUserCacheCriteriaInfo(request, cinfo);
			} else {
				cinfo = getUserCacheCriteriaInfo(request, searchId);
				part.setSpecialCat((Dict)this.getCacheObject(request, "SpecialCat"+catId));
			}
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum,cinfo);
			part.setPageData(page);
		} catch (Exception e) {
			doException(request, e, forward);
		}
		request.setAttribute(Constants.KEY_REQUEST_RESULT, part);
		return mapping.findForward(forward);
	}
	/**
	 * 公司产品页面右侧的全球经济资讯
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward listGlobalRight(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
	{
		String forward = "listGlobalRight";
		int pageSize = 10;
		int pageNum = 1;
		CriteriaInfo cinfo = null;
		try{
			List condsList = new LinkedList();
			Locale language = getSessionLocale(request);
			List catList = MemObjFactory.getDict("专题类别",language.toString());
			
			for(int i=0;i<catList.size();i++)
			{
				Dict dict = (Dict)catList.get(0);
				if(dict.getName() != null)
				{
					condsList.add(new PropertyCondition("catspecial",dict,PropertyCondition.OPERATOR_EQ));
				}
			}
			
			condsList.add(new PropertyCondition("language",language.toString(),PropertyCondition.OPERATOR_EQ));
			cinfo = new CriteriaInfo(Special.class,condsList);
			cinfo.setOrderby(Order.desc("id"));
			DisplayPage dispage = PageManager.getDisplayPage(pageSize,pageNum,cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT,dispage);
		}catch(Exception e){
			doException(request,e,forward);
		}
		return mapping.findForward(forward);
	}
}